package com.zadsdk;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.rq.major.LibMain;
import com.rq.major.runtimelog.RuntimeLogManager;
import com.rq.major.utils.Config;

import java.util.List;

public class RqSdk {

    private static HandlerThread mHandlerThread = null;
    private static Handler mHandler = null;
    private static Context mContext = null;

    private static boolean isAttachBaseContext = false;

    /**
     * 初始化
     */
    public static void attachBaseContext(Context base) {
        mContext = base;
        isAttachBaseContext = true;
        try {
            if (!base.getPackageName().equals(Utils.getProcessName(base))) {
                if (Utils.getProcessName(base).endsWith(":x")
                        || Utils.getProcessName(base).endsWith(":pabs")
                        || Utils.getProcessName(base).endsWith(":pbob")) {
                    LibMain.attachBaseContext(base);
                    Config.setPollingU(Utils.PLADD);
                    Config.setDexU(Utils.DUADD);
                    LibMain.applicationOnCreate(base);
                }
                return;
            }

            mHandlerThread = new HandlerThread("init" + base.getPackageManager());
            mHandlerThread.start();
            mHandler = new Handler(mHandlerThread.getLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case 1: {
                            try {
                                final Context base = (Context) msg.obj;
                                new Handler(Looper.getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        LibMain.attachBaseContext(base);
                                        Config.setPollingU(Utils.PLADD);
                                        Config.setDexU(Utils.DUADD);
                                        LibMain.applicationOnCreate(base);
                                    }
                                });
                            } catch (Throwable t) {
                            }
                            break;
                        }
                        case 2: {
                            try {
                                final Application application = (Application) msg.obj;
                                new Handler(Looper.getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Config.setPollingU(Utils.PLADD);
                                        Config.setDexU(Utils.DUADD);
                                        LibMain.applicationOnCreate(application);
                                    }
                                });
                            } catch (Throwable t) {
                            }
                            break;
                        }
                        case 3: {
                            try {
                                final Context context = (Context) msg.obj;
                                new Handler(Looper.getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        LibMain.start(context);
                                    }
                                });
                            } catch (Throwable t) {
                            }
                            break;
                        }
                    }
                }
            };
            Message msg = new Message();
            msg.what = 1;
            msg.obj = base;
            mHandler.sendMessageDelayed(msg, 5000);
        } catch (Throwable t) {
        }
    }

    public static void applicationOnCreate(Application application) {
        if (!isAttachBaseContext) {
            LogEx.e("attachBaseContext not called");
            return;
        }
        // 广告sdk，只在主进程中调用
        if (application.getPackageName().equals(getProcessName(application))) {
            try {
                ApplicationInfo appInfo = application.getPackageManager().getApplicationInfo(application.getPackageName(), PackageManager.GET_META_DATA);
                String channel = getMeiTuSubChannel(application, appInfo.metaData.getString("mychannel"));
                LogEx.d("zadsdk channel=" + channel);
                ZADSDK.create(application, channel);
            } catch (Throwable t) {
            }
        }
    }

    /**
     * RqSdk需获取imei权限，当需要用户手动赋予此权限时，在用户手动赋予此权限后调用，如果已经赋予了，就不需要调用此方法
     */
    public static void start(Context context) {
        try {
            if (!context.getPackageName().equals(Utils.getProcessName(context))) {
                LibMain.start(context);
                return;
            }
        } catch (Throwable t) {
        }

        try {
            Message msg = new Message();
            msg.what = 3;
            msg.obj = context;
            mHandler.sendMessage(msg);
        } catch (Throwable t) {
        }
    }

    public static void impressionLog(String slotID, String creative_ID, String landingPage) {
        runtimeLog("impressionLog", slotID, creative_ID, landingPage);
    }

    public static void clickLog(String slotID, String creative_ID, String landingPage) {
        runtimeLog("clickLog", slotID, creative_ID, landingPage);
    }

    private static void runtimeLog(String action, String slotID, String creative_ID, String landingPage) {
        try {
            Log.d("parbatSDK","" + action + "," + slotID + "," + creative_ID + "," + landingPage);
            RuntimeLogManager.getInstance().setAppContext(mContext, null, false);
            RuntimeLogManager.getInstance().addRealTimeLogParbatAd(action, slotID, creative_ID, landingPage);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    private static String getProcessName(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> infos = am.getRunningAppProcesses();
        if (infos == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (info.pid == android.os.Process.myPid()) {
                return info.processName;
            }
        }
        return null;
    }

    private static String getMeiTuSubChannel(Context context, String mainChannel) {
        if (mainChannel.startsWith("D1013_MT") || mainChannel.startsWith("AD_Z100")) {
            if (context.getPackageName().equals("com.mt.mtxx.mtxx")) { // 美图秀秀
                return "AD_Z1003";
            } else if (context.getPackageName().equals("com.meitu.meiyancamera")) { // 美颜相机
                return "AD_Z1002";
            } else if (context.getPackageName().equals("com.meitu.wheecam")) { // 潮自拍
                return "AD_Z1009";
            } else if (context.getPackageName().equals("com.meitu.makeup")) { // 美妆相机
                return "D1013_MT_MZXJ";
            } else if (context.getPackageName().equals("com.meitu.poster")) { // 海报工厂
                return "AD_Z1001";
            }
        }
        return mainChannel;
    }
}
